import type { Request, Response } from 'express';

const waitTime = (time: number = 100) => {
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve(true);
		}, time);
	});
};

// 模拟获取短信验证码
async function getFakeCaptcha(_req: Request, res: Response) {
	await waitTime(2000);
	return res.json('captcha-xxx');
}

// 是否为开发环境
const isDev = process.env.NODE_ENV == 'development';

/**
 * 获取当前用户的权限，如果为空代表没登录; 开发环境为admin角色
 */
const getAccess = () => {
	let access = isDev ? 'admin' : '';
	return access;
};

/**
 * 获取用户角色
 * RBAC模型：将权限分配给角色，再将角色分配给用户(一个用户存在多种角色)
 */
const getUserRoles = (isAdmin = false) => {
	let result = [];
	if (isAdmin) {
		result.push('admin');
	} else {
		result.push('others');
	}

	return result;
}

/**
 * 获取当前用户的权限
 */
const getPermission = (isAdmin = false) => {
	if (isAdmin) {
		return ['*'];
	}

	return [
		"app/index/list",
		"app/index/list",
	]
}

/**
 * 用户的菜单
 * @returns
 */
const getUserMenus = () => {
	const serverRoutes = [
		{
			name: '案例页面',
			path: '/demo2', // 正确的是demo1,这里尝试写错表示无demo1的权限
		},
		{
			name: '开始页面',
			path: '/start',
		},
	]

	return serverRoutes;
}


/** 截取当前Cookie */
const getCookies = (req: Request) => {
	const result: { [key: string]: any } = {};
	const cookieArr = String(req.headers.cookie).split(';').map(el => el.trim());
	for (let item of cookieArr) {
		let [key, val] = item.split('=');
		result[key.trim()] = val.trim();
	}
	return result;
}

// 代码中会兼容本地 service mock 以及部署站点的静态数据
export default {
	// 支持值为 Object 和 Array
	'GET /api/currentUser': (_req: Request, res: Response) => {
		const cookies = getCookies(_req);
		if (!cookies['user_token'] || !_req.headers['session']) {
			res.status(401).send({
				data: {
					isLogin: false,
				},
				errorCode: '401',
				errorMessage: '请先登录！',
				success: true,
			});
			return;
		}
		res.send({
			success: true,
			data: {
				name: 'Serati Ma',
				avatar:
					'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
				userid: '00000001',
				email: 'antdesign@alipay.com',
				signature: '海纳百川，有容乃大',
				title: '交互专家',
				group: '蚂蚁金服－某某某事业群－某某平台部－某某技术部－UED',
				tags: [
					{
						key: '0',
						label: '很有想法的',
					},
					{
						key: '1',
						label: '专注设计',
					},
					{
						key: '2',
						label: '辣~',
					},
					{
						key: '3',
						label: '大长腿',
					},
					{
						key: '4',
						label: '川妹子',
					},
					{
						key: '5',
						label: '海纳百川',
					},
				],
				notifyCount: 12,
				unreadCount: 11,
				country: 'China',
				geographic: {
					province: {
						label: '浙江省',
						key: '330000',
					},
					city: {
						label: '杭州市',
						key: '330100',
					},
				},
				address: '西湖区工专路 77 号',
				phone: '0752-268888888',

				// 权限相关
				access: getAccess(),
				roles: getUserRoles(isDev),
				permission: getPermission(isDev),

				// 菜单相关
				menus: getUserMenus(),
			},
		});
	},
	// GET POST 可省略
	'GET /api/users': [
		{
			key: '1',
			name: 'John Brown',
			age: 32,
			address: 'New York No. 1 Lake Park',
		},
		{
			key: '2',
			name: 'Jim Green',
			age: 42,
			address: 'London No. 1 Lake Park',
		},
		{
			key: '3',
			name: 'Joe Black',
			age: 32,
			address: 'Sidney No. 1 Lake Park',
		},
	],

	// 数据字典
	'GET /api/dict': [
		{
			key: 'gender',
			comment: '性别',
			list: [
				{ value: '1', text: '男' },
				{ value: '2', text: '女' },
			]
		},
		{
			key: 'switch',
			comment: '开关',
			list: [
				{ value: '1', text: '开启' },
				{ value: '0', text: '关闭' },
			]
		},
	],

	// 城市数据
	'GET /api/city': [
		{
			id: '10001',
			name: '湖北省',
			children: [
				{ id: '1000101', name: '武汉市' },
				{ id: '1000102', name: '黄冈市' },
				{ id: '1000103', name: '武穴市' },
			]
		},
		{
			id: '10002',
			name: '湖南省',
			children: [
				{ id: '1000201', name: '长沙市' },
				{ id: '1000202', name: '岳阳市' },
				{ id: '1000203', name: '衡阳市' },
			]
		},
	],

	// 登录接口
	'POST /api/login/account': async (req: Request, res: Response) => {
		const { password, username, type } = req.body;
		// await waitTime(2000);
		const session = Math.floor(Math.random() * 1000);
		if (password === 'ant.design' && username === 'admin') {
			// 过期时间 3600,000 毫秒（一小时）
			res.cookie("user_token", Math.floor(Math.random() * 1000000), { maxAge: 3600000, httpOnly: true });

			res.send({
				status: 'ok',
				session,
				type,
				currentAuthority: 'admin',
			});
			return;
		}
		if (password === 'ant.design' && username === 'user') {
			// 过期时间 3600,000 毫秒（一小时）
			res.cookie("user_token", Math.floor(Math.random() * 1000000), { maxAge: 3600000, httpOnly: true });

			res.send({
				status: 'ok',
				session,
				type,
				currentAuthority: 'user',
			});
			return;
		}
		if (type === 'mobile') {
			// 过期时间 3600,000 毫秒（一小时）
			res.cookie("user_token", Math.floor(Math.random() * 1000000), { maxAge: 3600000, httpOnly: true });

			res.send({
				status: 'ok',
				session,
				type,
				currentAuthority: 'admin',
			});
			return;
		}

		res.send({
			status: 'error',
			type,
			currentAuthority: 'guest',
		});
	},
	'POST /api/login/outLogin': (_req: Request, res: Response) => {
		res.send({ data: {}, success: true });
	},
	'POST /api/register': (_req: Request, res: Response) => {
		res.send({ status: 'ok', currentAuthority: 'user', success: true });
	},
	'GET /api/500': (_req: Request, res: Response) => {
		res.status(500).send({
			timestamp: 1513932555104,
			status: 500,
			error: 'error',
			message: 'error',
			path: '/base/category/list',
		});
	},
	'GET /api/404': (_req: Request, res: Response) => {
		res.status(404).send({
			timestamp: 1513932643431,
			status: 404,
			error: 'Not Found',
			message: 'No message available',
			path: '/base/category/list/2121212',
		});
	},
	'GET /api/403': (_req: Request, res: Response) => {
		res.status(403).send({
			timestamp: 1513932555104,
			status: 403,
			error: 'Forbidden',
			message: 'Forbidden',
			path: '/base/category/list',
		});
	},
	'GET /api/401': (_req: Request, res: Response) => {
		res.status(401).send({
			timestamp: 1513932555104,
			status: 401,
			error: 'Unauthorized',
			message: 'Unauthorized',
			path: '/base/category/list',
		});
	},

	'GET  /api/login/captcha': getFakeCaptcha,
};
